package controllers;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import debugs.OwnerDomainDebug;
import debugs.UserDebug;

import services.GoogleAnalytics;

import models.OwnerDomainModel;
import models.UserModel;

import entities.OwnerDomain;
import entities.ProfileAnalytic;
import entities.User;


public class ProcessAnalyticServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		String username = request.getUserPrincipal().getName();
		UserModel userModel = UserModel.getInstance();
		User user = userModel.getUser(username);
		
		//Get owner domain
		OwnerDomainModel ownerModel = OwnerDomainModel.getInstance();
		ArrayList<OwnerDomain> ownerDomains = ownerModel.getVertifyOwnerDomain(username);
		
		
		//Get account analytics 
		GoogleAnalytics analyticsService = new GoogleAnalytics(user);
		UserDebug.debug(user);
		TreeMap result = (TreeMap) analyticsService.getAccountFeed();
		TreeMap error = (TreeMap) result.get("error");
		ArrayList<ProfileAnalytic> profiles = (ArrayList<ProfileAnalytic>) result.get("profiles");
		
		for(int i = 0; i < profiles.size(); i++) {
			for (int j = 0; j < ownerDomains.size(); j++) {
				if (ownerDomains.get(j).getGoogleAnalyticPropertyId().equalsIgnoreCase(profiles.get(i).getWebPropertyId())) {
					ownerDomains.get(j).setAnalyticProfileId(profiles.get(i).getProfileId());
					ownerModel.insert(ownerDomains.get(j));
				}
			}
		}
		
		//Debug
		for (int i = 0; i < ownerDomains.size(); i++) {
			OwnerDomainDebug.debugWeb(ownerDomains.get(i), response);
		}
		
		//Get a set of the entries 
		Set set = error.entrySet(); 
		// Get an iterator 
		Iterator i = set.iterator(); 
		// Display elements 
		while(i.hasNext()) { 
			Map.Entry me = (Map.Entry)i.next(); 
			response.getWriter().print(me.getKey() + ":" + me.getValue());
			
		} 
		
		//response.sendRedirect("/profile/view");
	}
}
